package com.suny.sf_server.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.suny.Farm.vo.FarmSelectVO;
import com.suny.result.ResponseCode;
import com.suny.sf_server.redis.IRedisService;
import com.suny.utils.BeanConverter;
import jakarta.annotation.Resource;
import com.suny.DataDicVal.DataDicVal;
import com.suny.Farm.domain.Farm;
import com.suny.sf_server.service.FarmService;
import com.suny.sf_server.mapper.FarmMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.BeanUtils;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.suny.sf_server.service.DataDicValService;
import lombok.extern.slf4j.Slf4j;
import com.suny.Farm.dto.FarmAddDTO;
import com.suny.Farm.dto.FarmUpdateDTO;
import com.suny.Farm.vo.FarmVO;
import com.suny.exception.BusinessException;
import com.suny.result.PageDTO;
import com.suny.constant.RedisKeyConstant;
import com.suny.Farm.dto.FarmQueryDTO;

/**
* @author sun
* @description 针对表【farm(牧场信息表)】的数据库操作Service实现
* @createDate 2024-12-27 10:45:10
*/
@Service
@Slf4j
public class FarmServiceImpl extends ServiceImpl<FarmMapper, Farm> implements FarmService {
    
    @Resource
    private DataDicValService dataDicValService;
    
    @Resource
    private IRedisService redisService;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(FarmAddDTO dto) {
        //校验牲畜品种是否存在
         if (!dataDicValService.getHasDataDicValID(dto.getValId())){
             throw new BusinessException("牲畜品种不存在");
         }
         //  "area":321 ,
        //  "breedingScale": 8908,参数只能为数字

        if (!String.valueOf(dto.getArea()).matches("^[1-9]\\d*$")) {
            throw new BusinessException("场地面积格式错误");
        }
        if (!String.valueOf(dto.getBreedingScale()).matches("^[1-9]\\d*$")) {
            throw new BusinessException("养殖规模格式错误");
        }

        // 验证牲畜品种是否存在且启用
        DataDicVal dicVal = dataDicValService.getById(dto.getValId());
        if (dicVal == null || dicVal.getStatus() != 1) {
            throw new BusinessException("牲畜品种未启用");
        }
        
        // 验证牧场名称是否重复
        checkNameExists(dto.getName(), null);
        // 验证城市是否合法
        checkCity(dto.getCity(),dto.getProvince(),dto.getDistrict());
        
        // 保存牧场信息
        Farm farm = new Farm();
        BeanUtils.copyProperties(dto, farm);
        farm.setAmountLivestock(0);
        farm.setStatus(1);
        farm.setCreatedTime(new Date());
        farm.setUpdatedTime(new Date());
        
        save(farm);
        
        // 清除相关缓存
        clearCache(null);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(FarmUpdateDTO dto) {
        //校验牲畜品种是否存在
        if (!dataDicValService.getHasDataDicValID(dto.getValId())){
            throw new BusinessException("牲畜品种不存在");
        }
        // 验证牧场是否存在
        Farm farm = getById(dto.getId());
        if (farm == null) {
            throw new BusinessException("牧场不存在");
        }
        
        // 验证牲畜品种是否存在且启用
        DataDicVal dicVal = dataDicValService.getById(dto.getValId());
        if (dicVal == null || dicVal.getStatus() != 1) {
            throw new BusinessException("牲畜品种不存在或未启用");
        }
        
        // 验证牧场名称是否重复
        checkNameExists(dto.getName(), dto.getId());
        // 验证养殖规模是否大于等于场内牲畜数量
        checkBreedingScale(farm,dto);
        // 验证城市是否合法
        checkCity(dto.getCity(),dto.getProvince(),dto.getDistrict());
        // 更新牧场信息
        BeanUtils.copyProperties(dto, farm);
        farm.setUpdatedTime(new Date());
        
        updateById(farm);
        
        // 清除相关缓存
        clearCache(dto.getId());
        redisService.remove(RedisKeyConstant.FARM_DETAIL_PREFIX + dto.getId());
    }

    private void checkCity(String city, String province, String district) {
        //省县区字段校验
        if (!city.matches("^[\\u4e00-\\u9fa5]{1,20}$") || !province.matches("^[\\u4e00-\\u9fa5]{1,20}$") || !district.matches("^[\\u4e00-\\u9fa5]{1,20}$")) {
            throw new BusinessException("城市信息格式错误");
        }
        if (!city.matches("^[\\u4e00-\\u9fa5]+$") || !province.matches("^[\\u4e00-\\u9fa5]+$") || !district.matches("^[\\u4e00-\\u9fa5]+$")) {
            throw new BusinessException("城市信息格式错误");
        }
    }

    private void checkBreedingScale(Farm farm, FarmUpdateDTO dto) {
        if (!Objects.equals(farm.getBreedingScale(), dto.getBreedingScale())) {
            // 验证养殖规模是否大于等于场内牲畜数量
            if (dto.getBreedingScale() < farm.getAmountLivestock()) {
                throw new BusinessException("养殖规模不能小于场内牲畜数量");
            }
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(Integer farmId, Integer status) {
        if (farmId == null || status == null) {
            throw new BusinessException(ResponseCode.ILLEGAL_PARAMETER.getInfo());
        }
        Farm farm = getById(farmId);
        if (farm == null) {
            throw new BusinessException("牧场不存在");
        }
        if (status != 0 && status != 1) {
            throw new BusinessException("状态值错误");
        }
        if (Objects.equals(farm.getStatus(), status)) {
            throw new BusinessException("状态值未改变");
        }
        
        // 如果要停用，检查是否有未出栏牲畜
        if (status == 0 && farm.getAmountLivestock() > 0) {
            throw new BusinessException("牧场内还有未出栏牲畜，不能停用");
        }
        
        farm.setStatus(status);
        farm.setUpdatedTime(new Date());
        updateById(farm);
        
        // 清除相关缓存
        clearCache(farmId);
        redisService.remove(RedisKeyConstant.FARM_DETAIL_PREFIX + farmId);
    }
    
    @Override
    public Page<FarmVO> getList(PageDTO pageDTO) {
        // 1. 参数校验
        if (pageDTO == null || pageDTO.getPageNumber() <= 0 || pageDTO.getPageSize() <= 0) {
            throw new BusinessException(ResponseCode.ILLEGAL_PARAMETER.getInfo());
        }
        
        // 2. 生成包含分页参数的缓存key
        String cacheKey = String.format("%s:%d:%d", 
            RedisKeyConstant.FARM_LIST,
            pageDTO.getPageNumber(),
            pageDTO.getPageSize());
        
        // 3. 尝试从缓存获取
        if (redisService.isExists(cacheKey)) {
            return redisService.getValue(cacheKey);
        }
        
        // 4. 查询数据库
        Page<Farm> page = new Page<>(pageDTO.getPageNumber(), pageDTO.getPageSize());
        IPage<FarmVO> voPage = baseMapper.selectFarmVOPage(page);
        
        // 5. 处理空结果缓存
        if (voPage != null && voPage.getTotal() > 0) {
            redisService.setValue(cacheKey, voPage, RedisKeyConstant.CACHE_TIME);
        } else {
            redisService.setValue(cacheKey, voPage, RedisKeyConstant.EMPTY_CACHE_TIME);
        }
        
        return (Page<FarmVO>) voPage;
    }
    
    @Override
    public Page<FarmVO> getListByCondition(FarmQueryDTO query) {
        // 1. 参数校验
        if (query == null || query.getPageSize() == null || query.getPageNumber() == null||query.getPageNumber() <= 0 || query.getPageSize() <= 0) {
            throw new BusinessException(ResponseCode.ILLEGAL_PARAMETER.getInfo());
        }
        
        // 2. 生成包含查询条件的缓存key
        String cacheKey = String.format("%s:%s:%d:%d", 
            RedisKeyConstant.FARM_LIST,
            query.hashCode(),
            query.getPageNumber(),
            query.getPageSize());
        
        // 3. 尝试从缓存获取
        if (redisService.isExists(cacheKey)) {
            return redisService.getValue(cacheKey);
        }
        
        // 4. 查询数据库
        Page<Farm> page = new Page<>(query.getPageNumber(), query.getPageSize());
        IPage<FarmVO> voPage = baseMapper.selectFarmVOPageByCondition(page, query);
        
        // 5. 处理空结果缓存
        if (voPage != null && voPage.getTotal() > 0) {
            redisService.setValue(cacheKey, voPage, RedisKeyConstant.CACHE_TIME);
        } else {
            redisService.setValue(cacheKey, voPage, RedisKeyConstant.EMPTY_CACHE_TIME);
        }
        
        return (Page<FarmVO>) voPage;
    }

    @Override
    public List<FarmSelectVO> getFarmBySelect() {
        String cacheKey = RedisKeyConstant.FARM_SELECT;
        if (redisService.isExists(cacheKey)) {
            return redisService.getValue(cacheKey);
        }
        LambdaQueryWrapper<Farm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Farm::getStatus, 1);
        List<Farm> farms = baseMapper.selectList(wrapper);
        if (farms == null) {
            throw new BusinessException("牧场列表为空");
        }
        List<FarmSelectVO> list = BeanConverter.convertList(farms, FarmSelectVO.class);
        redisService.setValue(cacheKey, list, RedisKeyConstant.CACHE_TIME);
        return list;
    }

    @Override
    public List<FarmVO> getEnableFarms() {
        String cacheKey = RedisKeyConstant.FARM_ENABLE_LIST;
        if (redisService.isExists(cacheKey)) {
            return redisService.getValue(cacheKey);
        }
        
        List<FarmVO> list = baseMapper.selectEnableFarms();
        redisService.setValue(cacheKey, list, RedisKeyConstant.CACHE_TIME);
        return list;
    }
    
    @Override
    public FarmVO getDetail(Integer farmId) {
        String cacheKey = RedisKeyConstant.FARM_DETAIL_PREFIX + farmId;
        if (redisService.isExists(cacheKey)) {
            return redisService.getValue(cacheKey);
        }
        
        FarmVO vo = baseMapper.selectFarmVOById(farmId);
        if (vo != null) {
            redisService.setValue(cacheKey, vo, RedisKeyConstant.CACHE_TIME);
        }
        return vo;
    }

    @Override
    public Boolean getHasFarmByValId(Integer valId) {
        LambdaQueryWrapper<Farm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Farm::getValId, valId);
        return count(wrapper) > 0;
    }

    private void checkNameExists(String name, Integer excludeId) {
        LambdaQueryWrapper<Farm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Farm::getName, name);
        
        if (excludeId != null) {
            wrapper.ne(Farm::getId, excludeId);
        }
        
        if (count(wrapper) > 0) {
            throw new BusinessException("牧场名称已存在");
        }
    }
    
    /**
     * 清除牧场相关缓存
     */
    private void clearCache(Integer farmId) {
        // 使用模式匹配删除所有牧场列表缓存
//        redisService.removePattern(RedisKeyConstant.FARM);
        redisService.removePattern(RedisKeyConstant.FARM_DETAIL_PREFIX + farmId);
        redisService.remove(RedisKeyConstant.FARM_ENABLE_LIST);
        redisService.removePattern(RedisKeyConstant.FARM_LIST + ":*");
        redisService.removePattern(RedisKeyConstant.FARM_SELECT );
    }
}




